package com.wj.requestMappingConfig;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.mvc.condition.RequestCondition;

/*================================================================
说明：请求条件匹配器

作者          时间             	  注释
温为菁      2021-04-04		  创建
==================================================================*/
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {

    private int[] apiVersions;
    
    private static String VERSION_PREFIX="v";

    ApiVersionCondition(int[] apiVersion) {
        this.apiVersions = apiVersion;
    }
    /**
     * 最近优先原则，方法定义的 @ApiVersion > 类定义的 @ApiVersion
     */
    @Override
    public ApiVersionCondition combine(ApiVersionCondition other) {
        return new ApiVersionCondition(other.getApiVersions());
    }
    /**
     * 获得符合匹配条件的ApiVersionCondition
     */
    @Override
    public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
    	String requestURI = request.getRequestURI();
    	int lastIndexOf = requestURI.lastIndexOf("/");
    	String regUrl = requestURI.substring(lastIndexOf+1, requestURI.length());//截取请求路径的最后一层
    	
        if (regUrl.startsWith(VERSION_PREFIX)) {
        	int version = Integer.valueOf(regUrl.replaceFirst(VERSION_PREFIX, ""));
        	
        	for (int i : apiVersions) {
				if(i==version) {
					return this;
				}
			}
        }
        return null;
    }
    /**
     * 当出现多个符合匹配条件的ApiVersionCondition，优先匹配支持版本号多的
     */
    @Override
    public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
    	
    	return other.getApiVersions().length - getApiVersions().length;
    	
    }
    
	public int[] getApiVersions() {
		return apiVersions;
	}
	public void setApiVersions(int[] apiVersions) {
		this.apiVersions = apiVersions;
	}
    
    
}
